<template>
  <div class="line">
    <el-select v-model="value[0]" @change="handlePrevChange" placeholder="省" clearable :style="{ flexGrow: '1', marginRight: '10px' }">
      <el-option v-for="(item, index) in list" :key="index" :label="item.name" :value="item.code"></el-option>
    </el-select>
    <el-select v-model="value[1]" @change="handleCityChange" placeholder="市" clearable :style="{ flexGrow: '1', marginRight: '10px' }">
      <el-option v-for="(item, index) in cityList" :key="index" :label="item.name" :value="item.code"></el-option>
    </el-select>
    <el-select v-model="value[2]" placeholder="区（非必填）" clearable :style="{ flexGrow: '1' }">
      <el-option v-for="(item, index) in zoneList" :key="index" :label="item.name" :value="item.code"></el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  props: {
    list: Array,
  },
  data() {
    return {
      value: ['', '', ''],
      cityList: [],
      zoneList: [],
    }
  },
  watch: {
    value: {
      handler: function (value) {
        this.$emit('change', value)
      },
      deep: true,
    },
  },
  methods: {
    // 省份变化
    handlePrevChange(value) {
      this.value[1] = this.value[2] = ''
      const selected = this.list.find((item) => item.code === value)
      if (!selected) {
        return []
      }
      this.cityList = selected.children
    },
    // 城市变化
    handleCityChange(value) {
      this.value[2] = ''
      const selected = this.cityList.find((item) => item.code === value)
      if (!selected) {
        return []
      }
      this.zoneList = selected.children
    },
    setValue(value) {
      this.value[0] = value[0]
      this.handlePrevChange(value[0])
      this.value[1] = value[1]
      this.handleCityChange(value[1])
      this.value[2] = value[2]
    },
    // 重置
    reset() {
      this.value = ['', '', '']
      this.cityList = this.zoneList = []
    },
  },
}
</script>

<style></style>
